<?php

namespace app\topics\middle;

class FaqInfoMiddle extends \app\base\middle\BaseMiddle {

    private $info = [];

    protected function meta() {
        $info = $this->getInfo();
        $this->setMeta($info['title']);
        $this->setName('问答');
        $this->setCrumb([
            [
                'name' => $info['title'],
                'url' => URL
            ]
        ]);
        return $this->run([
            'pageInfo' => $this->pageInfo
        ]);
    }

    private function getInfo() {
        if($this->info) {
            return $this->info;
        }
        $id = intval($this->params['id']);
        $info = target('topics/TopicsDetail')->getWhereInfo([
            'A.detail_id' => $id,
            'A.type' => 'faq'
        ]);
        $this->info = $info;
        return $info;
    }

    protected function data() {
        $info = $this->getInfo();
        if (empty($info)) {
            return $this->stop('主题不存在', 404);
        }
        $id = $info['detail_id'];
        $nodeInfo = target('topics/TopicsNode')->getWhereInfo([
            'A.node_id' => $info['node_id']
        ]);
        if (empty($nodeInfo)) {
            return $this->stop('节点不存在', 404);
        }

        $replyList = target('topics/TopicsDetailReply')->loadList([
            'A.detail_id' => $id
        ],0, 'A.create_time asc');

        $replyInfo = end($replyList);

        $contentInfo = target('topics/TopicsDetailFaq')->getWhereInfo([
            'detail_id' => $id
        ]);

        $answerList = [];
        if ($contentInfo['answer']) {
            $answerList = target('topics/TopicsDetailReply')->loadList([
                '_sql' => 'A.reply_id in ('.$contentInfo['answer'].')'
            ], 0, 'A.create_time asc');


            $replyWhere['_sql'] = 'A.reply_id NOT IN ('.$contentInfo['answer'].')';
        }

        $otherList = target('topics/TopicsDetail')->loadList([
            'A.user_id' => $info['user_id']
        ], 10, 'A.create_time desc');

        $detailList = target('topics/TopicsDetail')->loadList(['A.node_id' => $info['node_id']], 10, 'A.create_time desc');

        target('topics/TopicsDetail')->where(['detail_id' => $id])->setInc('views');

        $manageUser = explode(',', $this->params['manage_user']);
        $moderator = explode(',', $nodeInfo['moderator']);
        $manageIds = array_merge($manageUser, $moderator);

        return $this->run([
            'info' => $info,
            'contentInfo' => $contentInfo,
            'replyList' => $replyList,
            'replyInfo' => $replyInfo,
            'otherList' => $otherList,
            'detailList' => $detailList,
            'answerList' => $answerList,
            'manageIds' => $manageIds,
        ]);
    }

}